<template>
	<scroll-view class="scroll-view" scroll-y>
		<!-- 已登录： 显示购物车 -->
		<template v-if="isAlreadyLogin">
			<!-- 购物车列表 -->
			<view class="cart-list" v-if="true">
				<view v-for="(item, index) in shopCarList" 
					:key="item.fourthId"
					:class="{ 'swipe-panel': true, 'swipe-panel__active': item.isDelete }" 
					@touchstart="touchStart"
					@touchend="touchEnd($event, index)" 
					@click="delCancle(index)">
					<view class="goods">
						<!-- 选中状态 -->
						<text :class="{ checkbox: true, checked: item.selected }" @tap="changeRadio(index)"></text>
						<view class="goodsDetail">
							<image mode="aspectFill" class="goodsImage" :src="picBaseUrl + item.url" />
							<view class="meta">
								<view class="name ellipsis">
									<text class="serviceCategory">{{ item.parentTopName }}</text>
									{{ item.secondParentName }}
								</view>
								<view class="attrsText ellipsis">{{ item.fourthName }}</view>
								<view class="price">{{ item.price + '.00'}}</view>
							</view>
						</view>
						<!-- 商品数量加减 -->
						<view class="count">
							<text :style="{color: item.quantity === 1 ? '#ccc': '#444'}" class="text" @tap.prevent.stop="reduceShopCar(index, item.fourthId)">-</text>
							<view class="input">{{ item.quantity }}</view>
							<text class="text"  @tap.prevent.stop="addShopCar(index, item.fourthId)">+</text>
						</view>
					</view>
					<!-- 删除按钮 -->
					<button :class="{ 'delete-box': true, 'delete__active': item.isDelete }" @click="deleteShop(item.fourthId)">删除</button>
				</view>
			</view>
		</template>
		<!-- 未登录: 提示登录 -->
		<view class="login-blank" v-else>
			<text class="text">登录后可查看购物车中的商品</text>
			<navigator url="/pages/components/zuhe" hover-class="none">
				<button class="button">去登录</button>
			</navigator>
		</view>
		<!-- 提交订单 -->
		<view class="submitOrder">
			<view class="allSelected">
				<radio value="r2" :checked="allSelected" color="#108ee9" @click="changeAllSelected" />
				<text>全选</text>
			</view>
			<view class="meet">
				<text class="meet">合计: ￥{{ meet }}</text>
			</view>
			<navigator class="btn" :url="'/pages/components/n-settlementCenter?goodIds=' + encodeURIComponent(JSON.stringify(selectedGoodIds))">
				<button>结算</button>
			</navigator>
		</view>
	</scroll-view>
</template>

<script setup lang="ts">
	import { ref, computed, watch, reactive } from "vue"
	import { onShow } from '@dcloudio/uni-app';
	import { addShopNum, delShopCar, listShopCar, reduceShopNum } from "@/api/http/shopCar"
	import { Shop } from "@/api/types/Shop"
	import { picBaseUrl } from "@/api/request"
	
	/** 控制登录状态显示不同页面 */
	let isAlreadyLogin = ref(false);
	onShow(() => {
		isAlreadyLogin.value = uni.getStorageSync('userId') ? true : false;
		if (isAlreadyLogin.value) getShopCarList()
	})
	
	const userId = uni.getStorageSync('userId');
	const isUserInfoAvailable = computed(() => {
		return userId ? true : false;
	})
	
	let shopCarList = ref<Shop.shopCarType[]>()
	/**
	 * @description 滑动删除操作 
	 * startX：触摸起始水平方向位置
	 * touchStart：触摸开始事件
	 * touchEnd：触摸结束事件
	 * resetIsDelete：每件商品删除按钮互斥事件
	 * delCancle：取消删除按钮事件
	 */
	// 触屏初始位置
	let startX = ref<number>(0)
	const touchStart = (e : TouchEvent) => {
		e.preventDefault()
		e.stopPropagation()
		if (e.touches.length == 1) {
			startX.value = e.touches[0].clientX;
		}
	}
	const touchEnd = (e : TouchEvent, i : number) => {
		e.preventDefault()
		e.stopPropagation()
		if (e.changedTouches.length == 1) {
			let endX = e.changedTouches[0].clientX
			let distance = endX - startX.value
			if (Math.abs(distance) > 20) {
				if (distance < 0) {
					resetIsDelete()
					shopCarList.value[i].isDelete = true
				} else {
					resetIsDelete()
					shopCarList.value[i].isDelete = false
				}
			}
		}
	}
	const resetIsDelete = () => {
		let index = shopCarList.value.findIndex(item => item.isDelete === true)
		if (index > -1) {
			shopCarList.value[index].isDelete = false
		}
	}
	const delCancle = (i : number) => {
		resetIsDelete()
		shopCarList.value[i].isDelete = false
	}
	
	// const getShopCarList = async (): Promise<Shop.shopCarType[]> => {
	// 	let data = await listShopCar(1);
	// 	return data || [];  // 确保返回的是数组
	// };
	
	// const deleteShop = async (goodsId: number) => {
	// 	if (shopCarList.value.length === 0) return;
	// 	await delShopCar(1, goodsId);  // 删除商品
	// 	shopCarList.value = await getShopCarList();  // 获取新的购物车列表并更新
	// };
	
	const deleteShop = async (goodsId : number) => {
		
		if (shopCarList.value.length === 0) return;
		await delShopCar(1, goodsId)
		await getShopCarList()
	}

	/**
	 * @description 获取购物车列表
	 */
	const getShopCarList = async () => {
		// if(uni.getStorageSync('userId')==null){
		// 	uni.setStorageSync('userId',0)
		// }
		let data = await listShopCar(uni.getStorageSync('userId'))
		shopCarList.value = data || []
		shopCarList.value.map(item => {
			return {
				...item,
				'selected': false,
				'isDelete': false
			}
		})
	}

	/**
	 * @description: 单品radio激活与失活状态现实控制
	 */
	const changeRadio = (i : number) => {
		shopCarList.value[i].selected = !shopCarList.value[i].selected
	}
	/**
	 * @description 记录所有被选中商品的id 
	 */
	const selectedGoodIds = computed(() => {
		const arr = [] 
		shopCarList.value?.forEach(item => {
			item.selected && arr.push(item.fourthId)
		})
		return arr
	})
	/**
	 * @description: 全选功能处理
	 */
	//** meet 合计 **//
	let meet = computed(() => {
		let count = 0
		shopCarList.value?.forEach(item => {
			if (item.selected) {
				count = count + item.price * item.quantity
			}
		})
		return count
	})
	//** 全选radios激活与失活显示状态 **//
	let allSelected = ref<boolean>(false)
	//** watchAllSelected 记录每个单品radio均被激活 **//
	let watchAllSelected = computed(() => {
		if (shopCarList.value && shopCarList.value.length > 0) return shopCarList.value?.every(item => item.selected === true)
	})
	//** 监听每一项radio均激活后，激活全选按钮 **//
	watch(watchAllSelected, (bool) => {
		allSelected.value = bool
	})
	//** 全选radio单击事件 **//
	const changeAllSelected = () => {
		allSelected.value = !allSelected.value
		shopCarList.value.forEach(item => {
			item.selected = allSelected.value
		})
	}

	/**
	 * useTo: 控制计数器
	 */
	const reduceShopCar = async (index:number, id: number) => {
		if (shopCarList.value[index].quantity <= 1) return;
		await reduceShopNum({ userId: uni.getStorageSync('userId'), goodId: id})
		await getShopCarList()
	}
	const addShopCar = async (index : number, id: number) => {
		await addShopNum({ userId: uni.getStorageSync('userId'), goodId: id})
		await getShopCarList()
	}

	
	/**
	 * @description 删除处理事件 
	 */
	
</script>

<style scoped lang="scss">
	:hoot {
		height: 100vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		background-color: #f7f7f8;
	}

	.scroll-view {
		flex: 1;
	}

	// 商品列表
	.cart-list {
		margin-bottom: 120rpx;
		padding: 0 20rpx;

		// 每个商品面板
		.swipe-panel {
			position: relative;
			margin-top: 22rpx;
			overflow: hidden;

			// 删除按钮
			.delete-box {
				position: absolute;
				top: 0;
				right: 0;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-right: -130rpx;
				width: 130rpx;
				height: 100%;
				border-radius: 0;
				border-top-right-radius: 10rpx;
				border-bottom-right-radius: 10rpx;
				background-color: #f56c6c;
				font-size: 22rpx;
				color: #fff;
				transition: all 0.2s linear;
			}

			.delete__active {
				margin-right: 0;
			}
		}
		.swipe-panel__active {
			margin-left: -80rpx;
		}
		.goods {
			position: relative;
			display: flex;
			padding: 20rpx 20rpx 20rpx 80rpx;
			border-radius: 10rpx;
			background-color: #fff;
			position: relative;

			// 单选按钮
			.checkbox {
				position: absolute;
				top: 50%;
				left: 16rpx;
				transform: translateY(-50%);
				width: 46rpx;
				height: 46rpx;
				text-align: center;
				line-height: 1;
				border-radius: 50%;
				border: 1px solid rgba($uni-primary, .66);
			}
			.checked {
				@extend .checkbox;
				background-color: $uni-primary;
				&::before {
					display: inline-block;
					content: "";
					width: 40%;
					height: 20%;
					border-left: 6rpx solid #fff;
					border-bottom: 6rpx solid #fff;
					border-bottom-left-radius: 6rpx;
					transform: rotate(-45deg);
				}
			}

			// 商品详细信息
			.goodsDetail {
				display: flex;
			}

			.goodsImage {
				width: 200rpx;
				height: 200rpx;
			}

			.meta {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				margin-left: 20rpx;
			}

			// 商品服务类型与名称
			.name {
				height: 50rpx;
				font-size: 26rpx;

				.serviceCategory {
					padding: 8rpx 16rpx;
					font-size: 20rpx;
					color: #fff;
					border-radius: 40rpx;
					background-color: $uni-primary;
				}
			}

			// 细分部分
			.attrsText {
				line-height: 1.8;
				padding: 0 15rpx;
				font-size: 24rpx;
				align-self: flex-start;
				border-radius: 4rpx;
				color: #888;
				background-color: #dfdfdf;
			}

			// 价格部分
			.price {
				line-height: 1;
				font-size: 26rpx;
				color: #f56c6c;

				&::before {
					content: '￥';
					font-size: 80%;
				}
			}
		}

		// 计数器
		.count {
			position: absolute;
			bottom: 20rpx;
			right: 20rpx;

			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 220rpx;
			height: 48rpx;

			.text {
				height: 100%;
				padding: 0 20rpx;
				font-size: 32rpx;
				color: #444;
				background-color: #f6f6f6;
			}

			.input {
				flex: 1;
				height: 48rpx;
				text-align: center;
				line-height: 48rpx;
				border-radius: 4rpx;
				font-size: 24rpx;
				color: #444;
				border-left: 2px solid #fff;
				border-right: 2px solid #fff;
				background-color: #f6f6f6;
			}
		}
	}

	// 空状态
	.cart-blank,
	.login-blank {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		height: 60vh;

		.image {
			width: 400rpx;
			height: 281rpx;
		}

		.text {
			color: #444;
			font-size: 26rpx;
			margin: 20rpx 0;
		}

		.button {
			width: 240rpx !important;
			height: 60rpx;
			line-height: 60rpx;
			margin-top: 20rpx;
			font-size: 26rpx;
			border-radius: 60rpx;
			color: #fff;
			background-color: #27ba9b;
		}
	}

	// 提交订单
	.submitOrder {
		position: fixed;
		left: 0;
		bottom: 0;
		padding: 10rpx 20rpx;
		width: 100% !important;
		height: 100rpx;
		background: #fff;
		box-shadow: 0 -2px 10px #dfdfdf !important;
		box-sizing: border-box;
		@include flex;
		align-items: center;

		.allSelected {
			text {
				margin-left: 20rpx;
				vertical-align: middle;
			}
		}

		.meet {
			color: red;
		}

		.btn {
			button {
				width: 200rpx;
				color: #fff;
				letter-spacing: 2px;
				background-color: $uni-primary;
			}
		}
	}
</style>